﻿/***************************************************************************
 * 文件名：MainForm
 * 功能：
 * 说明： 辅助工具主窗体
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/9 08:50:43
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.XtraEditors;
using RunMethodLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Util;
using Point = System.Drawing.Point;
using Size = System.Drawing.Size;

namespace AuxiliaryTools
{
	public partial class MainForm : XtraForm
	{
		#region Const

		/// <summary>
		/// 配置文件夹
		/// </summary>
		private const string c_Config = "Config";

		/// <summary>
		/// 配置文件名称
		/// </summary>
		private const string c_ConfigurationFileName = "ToolsConfiguration.xml";

		/// <summary>
		/// 按钮前缀
		/// </summary>
		private const string c_RecentlyUsed = "btnRecentlyUsed";

		/// <summary>
		/// 搜索
		/// </summary>
		private const string c_Search = "btnSearch";

		/// <summary>
		/// 按钮前缀
		/// </summary>
		private const string c_Fixed = "btnFixed";

		#endregion

		#region Propertys

		/// <summary>
		/// 所有工具列表
		/// </summary>
		public List<ToolModel> ToolList { get; set; } = new List<ToolModel>();

		/// <summary>
		/// 工具配置文件路径
		/// </summary>
		private string _configurationFilePath;

		/// <summary>
		/// 最小化程序到托盘的图标
		/// </summary>
		private NotifyIcon trayIcon;
		private ContextMenuStrip trayMenu;

		#endregion

		#region API调用

		[System.Runtime.InteropServices.DllImport("user32.dll")]
		public static extern bool ReleaseCapture();

		[System.Runtime.InteropServices.DllImport("user32.dll")]
		public static extern void SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

		public const int WM_NCLBUTTONDOWN = 0xA1;
		public const int HT_CAPTION = 0x2;

		#endregion

		#region Win

		public MainForm()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Load事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MainForm_Load(object sender, System.EventArgs e)
		{
			#region 允许拖动事件

			this.MouseDown += MainForm_MouseDown;
			this.panelControl1.MouseDown += MainForm_MouseDown;
			this.panelControl2.MouseDown += MainForm_MouseDown;
			this.groupControl1.MouseDown += MainForm_MouseDown;
			this.groupControl2.MouseDown += MainForm_MouseDown;
			this.txtSearchFunction.MouseDown += MainForm_MouseDown;

			#endregion

			#region 加载工具配置

			LoadToolConfiuration();

			#endregion

			#region 初始化最近使用功能

			InitLayoutControlGroup();

			#endregion

			#region 最小化托盘

			// 创建托盘菜单
			trayMenu = new ContextMenuStrip();
			trayMenu.Items.Add("还原窗口", null, OnRestore);
			trayMenu.Items.Add("退出程序", null, OnExit);

			// 创建托盘图标
			trayIcon = new NotifyIcon
			{
				Text = "辅助工具",
				Icon = new Icon(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "工具.ico")),
				ContextMenuStrip = trayMenu,
				Visible = true
			};

			// 双击托盘图标还原窗口
			trayIcon.DoubleClick += (s, t) => ShowMainWindow();

			#endregion
		}

		#endregion

		#region Methods

		/// <summary>
		/// 加载工具配置
		/// </summary>
		private void LoadToolConfiuration()
		{
			try
			{
				string localDir = FileHelperUtil.GetAppDataFolderPath();
				if (string.IsNullOrEmpty(localDir) || !Directory.Exists(localDir))
				{
					return;
				}

				string configDir = Path.Combine(localDir, UtilConst.AuxiliaryTools, c_Config);
				_configurationFilePath = Path.Combine(configDir, c_ConfigurationFileName);
				if (!Directory.Exists(configDir))
				{
					Directory.CreateDirectory(configDir);
				}

				if (!File.Exists(_configurationFilePath))
				{

					///拷贝本地程序配置文件至Local目录下
					string programConfigurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_Config, c_ConfigurationFileName);
					//构建工具配置文件路径
					if (string.IsNullOrEmpty(_configurationFilePath) && !File.Exists(_configurationFilePath))
					{
						return;
					}

					File.Copy(programConfigurationFilePath, _configurationFilePath, true);
				}

				//读取配置文件
				ToolList = AuxiliaryToolUtil.GetToolConfiguration(_configurationFilePath);
				if (ToolList == null || ToolList.Count == 0)
				{
					MessageBox.Show("没有加载到任何工具配置，请检查配置文件是否正确。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("加载工具配置失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 初始化工具库
		/// </summary>
		private void InitLayoutControlGroup()
		{
			try
			{
				#region 判断是否显示 最近使用工具面板

				//判断是否显示最近使用工具的面板
				var recentlyUsedTools = ToolList?.Where(t => t.IsRecentlyUsed).OrderBy(p => p.Sort).ToList();
				var fixedTools = ToolList?.Where(t => t.IsFixed).ToList();
				this.groupControl1.Visible = recentlyUsedTools != null && recentlyUsedTools.Count > 0;
				this.groupControl1.Height = 120; //设置GroupControl1的高度

				#endregion

				#region 构建最近使用工具列表

				CreateSimpleButton(this.groupControl1, recentlyUsedTools, c_RecentlyUsed);

				#endregion

				#region 构建已固定工具列表

				CreateSimpleButton(this.groupControl2, fixedTools, c_Fixed);

				#endregion

			}
			catch (Exception ex)
			{
				XtraMessageBox.Show("初始化工具库失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 创建简单按钮
		/// </summary>
		/// <param name="control"></param>
		/// <param name="toolModels"></param>
		/// <param name="buttonPrefix"></param>
		private void CreateSimpleButton(GroupControl control, List<ToolModel> toolModels, string buttonPrefix)
		{
			try
			{
				if (control == null || toolModels?.Count == 0)
				{
					return;
				}
				//GroupCpntrol的宽、高
				int width = control.Width;
				int height = control.Height;

				//获取当前GroupControl1的位置
				int x = control.Location.X;
				int y = control.Location.Y;

				int count = width / 90;
				int originalHeight = 30;

				//循环添加按钮，默认添加最近使用的七个
				for (int i = 0; i < toolModels.Count; i++)
				{
					#region 创建按钮

					var tool = toolModels[i];
					if (tool == null)
					{
						continue;
					}

					//计算按钮的位置
					x = 10 + (i % count) * (80 + 10);
					y = 30 + (i / count) * (100 + 10);

					//构建按钮对象
					SimpleButton simple = new SimpleButton();
					simple.Location = new Point(x, y);
					simple.Name = string.Format("{0}{1}", buttonPrefix, i);
					simple.Size = new Size(80, 100);
					simple.Text = tool.Name;
					simple.ToolTip = tool.Name;
					simple.ImageOptions.ImageToTextAlignment = ImageAlignToText.TopCenter;
					simple.Margin = new Padding(5, 0, 0, 0);
					simple.Tag = tool.Name; //将工具名称作为Tag存储
					simple.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

					#endregion

					#region 添加图标

					//如果按钮的图片文件存在，则给按钮添加图片背景
					string imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, UtilConst.Image, tool.ImagePath);

					///若图片路径存在，则直接添加，若不存在则创建默认图片
					if (File.Exists(imagePath))
					{
						simple.ImageOptions.Image = Image.FromFile(imagePath);
					}
					else
					{
						string imageName = tool.Name + ".png";
						//检测是否已经生成默认图片
						imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, UtilConst.DefaultImage, imageName);

						if (!File.Exists(imagePath))
						{
							FileHelperUtil.GeneratorImage(imagePath, tool.Name);
						}
						simple.ImageOptions.Image = Image.FromFile(imagePath);
					}

					#endregion

					#region 按钮点击事件

					//点击事件
					simple.Click += (s, e) =>
					{
						try
						{
							#region 检测启动配置项

							//如果程序入口不为空，则启动对应的程序
							if (string.IsNullOrEmpty(tool.ToolFileDir) || string.IsNullOrEmpty(tool.ProgramEntrance))
							{
								return;
							}

							#endregion

							#region 执行启动程序

							//检测文件类型，判断是Exe文件还是dll
							bool isExeProgram = FileHelperUtil.IsProgramExe(tool.ProgramEntrance);

							switch (tool.StartMode)
							{
								case ProgramStartMode.IndependentThreads:
									{
										if (!isExeProgram)
										{
											MessageBox.Show($"{tool.Name}工具配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, tool.ProgramEntrance);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										Process.Start(programPath);

										break;
									}
								case ProgramStartMode.InterfaceCall:
									{
										//从程序入口配置中解析dll文件名称、调用入口
										var list = tool.ProgramEntrance.Split(';');
										if (list == null || list.Count() == 0 || list.Length != 2)
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										string dllFileName = list[0];
										string callClassName = list[1];

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir, dllFileName);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{tool.Name}工具程序入口配置的Dll文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//获取接口实例
										var IRunMethod4SingleForms = RunMethodUtil.GetExecutes(programPath, callClassName);
										if (IRunMethod4SingleForms?.Count == 0)
										{
											MessageBox.Show($"{tool.Name}调用点配置有误！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										if (IRunMethod4SingleForms[0] is IRunMethod4SingleForm singleForm)
										{
											// 通过事件手动解析依赖项
											AppDomain.CurrentDomain.AssemblyResolve += (sender, argsx) =>
											{
												string dependencyPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tool.ToolFileDir), $"{new AssemblyName(argsx.Name).Name}.dll");
												return File.Exists(dependencyPath) ? Assembly.LoadFrom(dependencyPath) : null;
											};

											if (!MainFormOption.Search2BringToFront(singleForm.FormType))
											{
												IRunMethod4SingleForms[0].Execute();
											}
										}
										break;
									}
								default:
									return;
							}

							#endregion

							#region 最小化至托盘、更新配置文件、刷新工具列表

							//最小化托盘
							this.WindowState = FormWindowState.Minimized;

							//构建更新内容
							Dictionary<string, string> valuePairs = new Dictionary<string, string>();
							valuePairs.Add("IsRecentlyUsed", "true");
							valuePairs.Add("Sort", (tool.Sort + 1).ToString());

							//更新工具配置文件（最近使用）
							AuxiliaryToolUtil.UpdateToolConfiguration(_configurationFilePath, simple.Tag.ToString(), valuePairs);

							this.BeginInvoke(new Action(() =>
							{
								//刷新最近使用工具列表
								RefreashGroupControl(this.groupControl1);
							}));

							#endregion
						}
						catch (Exception ex)
						{
							MessageBox.Show("启动工具失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					};

					#endregion

					#region 右键菜单

					ContextMenuStrip contextMenu = new ContextMenuStrip();
					
					if (buttonPrefix.Equals(c_RecentlyUsed))
					{
						//从最近使用中删除
						ToolStripMenuItem deleteOfRecently = new ToolStripMenuItem("从最近使用中删除");
						deleteOfRecently.Click += (s, e) =>
						{
							try
							{
								//构建更新内容
								Dictionary<string, string> valuePairs = new Dictionary<string, string>();

								valuePairs.Add("IsRecentlyUsed", "false");
								valuePairs.Add("Sort", "0");

								//更新工具配置文件（最近使用）
								AuxiliaryToolUtil.UpdateToolConfiguration(_configurationFilePath, simple.Tag.ToString(), valuePairs);

								this.BeginInvoke(new Action(() =>
								{
									//刷新最近使用工具列表
									RefreashGroupControl(this.groupControl1);
								}));
							}
							catch (Exception ex)
							{
								MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						};
						contextMenu.Items.Add(deleteOfRecently);
					}

					//检测是否已被固定
					if (tool.IsFixed)
					{
						//取消固定
						ToolStripMenuItem Unpin = new ToolStripMenuItem("取消固定");
						Unpin.Click += (s, e) =>
						{
							try
							{
								//构建更新内容
								Dictionary<string, string> valuePairs = new Dictionary<string, string>();

								valuePairs.Add("IsFixed", "false");

								//更新工具配置文件（最近使用）
								AuxiliaryToolUtil.UpdateToolConfiguration(_configurationFilePath, simple.Tag.ToString(), valuePairs);

								this.BeginInvoke(new Action(() =>
								{
									//刷新固定工具列表
									RefreashGroupControl(this.groupControl2);
								}));
							}
							catch (Exception ex)
							{
								MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						};
						contextMenu.Items.Add(Unpin);
					}
					else
					{
						//固定
						ToolStripMenuItem fixedItem = new ToolStripMenuItem("固定");
						fixedItem.Click += (s, e) =>
						{
							try
							{
								//构建更新内容
								Dictionary<string, string> valuePairs = new Dictionary<string, string>();

								valuePairs.Add("IsFixed", "true");

								//更新工具配置文件（最近使用）
								AuxiliaryToolUtil.UpdateToolConfiguration(_configurationFilePath, simple.Tag.ToString(), valuePairs);

								this.BeginInvoke(new Action(() =>
								{
									//刷新固定工具列表
									RefreashGroupControl(this.groupControl2);
								}));
							}
							catch (Exception ex)
							{
								MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						};
						contextMenu.Items.Add(fixedItem);
					}

					simple.ContextMenuStrip = contextMenu;

					#endregion

					#region 添加

					control.Controls.Add(simple);

					#endregion
				}

				int heightDifference = y - originalHeight;

				control.Height += heightDifference; //调整groupcontrol的高度
				this.Height += heightDifference; //调整窗体的高度
			}
			catch (Exception ex)
			{
				MessageBox.Show("添加工具按钮失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 刷新GroupControl
		/// </summary>
		private void RefreashGroupControl(GroupControl control)
		{
			try
			{
				LoadToolConfiuration();

				bool isClearAll = false;
				bool isClearGroupControl1 = false;
			   bool isClearGroupControl2 = false;
				//如果传递的为null.则清除全部
				if(control == null)
				{
					isClearAll = true;
				}
				else if (control.Name.Equals(this.groupControl1.Name))
				{
					isClearGroupControl1 = true;
				}
				else
				{
					isClearGroupControl2 = true;
				}

				if (isClearAll || isClearGroupControl1)
				{

					this.groupControl1.Controls.Clear();
					//判断是否显示最近使用工具的面板
					var recentlyUsedTools = ToolList?.Where(t => t.IsRecentlyUsed).OrderByDescending(p => p.Sort).ToList();
					this.groupControl1.Visible = recentlyUsedTools != null && recentlyUsedTools.Count > 0;
					CreateSimpleButton(this.groupControl1, recentlyUsedTools, c_RecentlyUsed);
				}

				if (isClearAll || isClearGroupControl2)
				{
					this.groupControl2.Controls.Clear();
					//已固定
					var fixedTools = ToolList?.Where(t => t.IsFixed).ToList();
					CreateSimpleButton(this.groupControl2, fixedTools, c_Fixed);
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 注册方法
		/// </summary>
		/// <param name="isRegisterPlugin"></param>
		private void RegisterMethod(bool isRegisterPlugin = false)
		{
			try
			{
				//获取已注册程序名称
				List<string> functionNameList = ToolList?.Select(p => p.Name).ToList();

				int selectTabIndex = isRegisterPlugin ? 0 : 1;

				//调用程序注册界面
				FMRegistrationProcedure fm = new FMRegistrationProcedure(functionNameList, _configurationFilePath, selectTabIndex);
				DialogResult result = fm.ShowDialog();
				if (result != DialogResult.OK)
				{
					return;
				}

				//刷新工具列表
				this.BeginInvoke(new Action(() =>
				{
					//刷新工具列表
					RefreashGroupControl(this.groupControl2);
				}));
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region 最小化托盘

		/// <summary>
		/// 窗体最小化时隐藏到托盘
		/// </summary>
		/// <param name="e"></param>
		protected override void OnResize(EventArgs e)
		{
			if (WindowState == FormWindowState.Minimized)
			{
				Hide();
				ShowInTaskbar = false; 
			}
			base.OnResize(e);
		}

		/// <summary>
		/// 恢复
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnRestore(object sender, EventArgs e) => ShowMainWindow();

		/// <summary>
		/// 显示窗口
		/// </summary>
		private void ShowMainWindow()
		{
			Show();
			WindowState = FormWindowState.Normal;
			ShowInTaskbar = true;
			BringToFront();
		}

		/// <summary>
		/// 退出程序
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnExit(object sender, EventArgs e)
		{
			trayIcon.Visible = false; // 移除托盘图标
			Application.Exit();
		}

		/// <summary>
		/// 窗体关闭时清理资源
		/// </summary>
		/// <param name="e"></param>
		protected override void OnFormClosing(FormClosingEventArgs e)
		{
			trayIcon.Dispose();
			base.OnFormClosing(e);
		}

		#endregion

		#region Event

		/// <summary>
		/// 窗体拖动事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MainForm_MouseDown(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				ReleaseCapture();
				SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
			}
		}

		/// <summary>
		/// 双击事件最小化托盘
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSetting_DoubleClick(object sender, EventArgs e)
		{
			FMPluginMarket fm = new FMPluginMarket(_configurationFilePath);
			fm.ShowDialog();
		}

		/// <summary>
		/// 导入配置文件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnImportConfiguration_Click(object sender, EventArgs e)
		{
			try
			{
				string folderPath = string.Empty;
				using (var folderDialog = new FolderBrowserDialog())
				{
					folderDialog.Description = "请选择文件夹";
					folderDialog.ShowNewFolderButton = true; // 允许新建文件夹

					if (folderDialog.ShowDialog() != DialogResult.OK)
					{
						return;
					}

					folderPath = folderDialog.SelectedPath;
				}

				if (!Directory.Exists(folderPath))
				{
					MessageBox.Show("当前选择的文件夹不存在或已被删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				//检查当前选择的文件夹是否存在文件
				bool isExist = FileHelperUtil.IsExistFile(folderPath);
				if (!isExist)
				{
					MessageBox.Show("当前选择的文件夹下没有任何文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				string auiliaryToolsDir = Path.Combine(FileHelperUtil.GetAppDataFolderPath(), UtilConst.AuxiliaryTools);
				
				//拷贝文件夹下的所有文件到指定目录
				FileHelperUtil.CopyFolder(folderPath, auiliaryToolsDir);

				MessageBox.Show("导入配置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 导出配置文件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnExportConfiguration_Click(object sender, EventArgs e)
		{
			try
			{
				string auiliaryToolsDir = Path.Combine(FileHelperUtil.GetAppDataFolderPath(),UtilConst.AuxiliaryTools);
				if (!Directory.Exists(auiliaryToolsDir))
				{
					MessageBox.Show("当前不存在自定义配置文件！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				string folderPath = string.Empty;
				using (var folderDialog = new FolderBrowserDialog())
				{
					folderDialog.Description = "请选择文件夹";
					folderDialog.ShowNewFolderButton = true; // 允许新建文件夹

					if (folderDialog.ShowDialog() != DialogResult.OK)
					{
						return;
					}

					folderPath = folderDialog.SelectedPath;
				}

				if (!Directory.Exists(folderPath))
				{
					MessageBox.Show("当前选择的文件夹不存在或已被删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				//拷贝文件夹下的所有文件到指定目录
				FileHelperUtil.CopyFolder(auiliaryToolsDir, folderPath);

				MessageBox.Show("导出配置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 一键启动环境
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnStartEnviroment_Click(object sender, EventArgs e)
		{
			try
			{
				
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 注册插件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnRegisterPlugin_Click(object sender, EventArgs e)
		{
			RegisterMethod(true);
		}

		/// <summary>
		/// 注册应用
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnRegister_Click(object sender, EventArgs e)
		{
			RegisterMethod();
		}

		/// <summary>
		/// 关闭
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSetting_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		#endregion

		/// <summary>
		/// 搜索框改变事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textEdit1_TextChanged(object sender, EventArgs e)
		{
			try
			{
				this.groupControl1.Visible = true;
				this.groupControl1.Controls?.Clear();

				string searchText = txtSearchFunction.Text;

				if (string.IsNullOrEmpty(searchText))
				{
					this.groupControl1.Text = "最近使用"; 
					var recentlyUsedTools = ToolList?.Where(t => t.IsRecentlyUsed).OrderBy(p => p.Sort).ToList();
					this.groupControl1.Visible = recentlyUsedTools != null && recentlyUsedTools.Count > 0;
					this.BeginInvoke(new Action(() =>
					{
						//刷新
						RefreashGroupControl(this.groupControl1);
					}));

					return;
				}

				this.groupControl1.Text = "最佳搜索结果";

				var searchList = ToolList?.Where(p=>p.Name.Contains(searchText)).ToList();

				#region 构建最近使用工具列表

				CreateSimpleButton(this.groupControl1, searchList, c_Search);

				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

	}
}
